package democache;

import democache.computer.Computable;
import democache.computer.ExpensiveFunction;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Brook
 * 演示concurrentHashMap重复计算
 */
public class DemoCache5<A, V> implements Computable<A, V> {

    private final Map<A, V> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public DemoCache5(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws Exception {
        System.out.println("进入缓存机制");
        V result = cache.get(arg);
        if(result == null){
            result = c.compute(arg);
            cache.put(arg,result);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        DemoCache5<String, Integer> demoCache2 = new DemoCache5(new ExpensiveFunction());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果："+result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("667");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第二次计算结果："+result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第三次计算结果："+result);
            }
        }).start();
    }
}
